import 'package:flexible/flexible.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_1_25_0/testWidget/pb/base/model.pb.dart';
import 'package:flutter_app_1_25_0/testWidget/pb/exercise_practise/model.pb.dart';
import 'package:logging/logging.dart';

Logger _log = Logger('Exercise');

/*
 * Create by weslywang on 2020/9/22
 * Copyright © Tencent
 *
 * Description: 富文本基本数据项显示组件
 */

class RichDataItemWidget extends StatelessWidget {
  RichDataItemWidget(
      {@required this.pageId,
      @required this.dataItem,
      this.prefix = '',
      this.practiseViewType,
      this.displayStyle = DisplayStyle.small,
      this.maxLines,
      this.enableClick = true,
      this.fillBlank = true});

  final DataItem dataItem;
  final String prefix;
  final String pageId;
  final PractiseViewType practiseViewType;
  final DisplayStyle displayStyle;
  final double defaultTextHeight = 1.5;
  final int maxLines;
  final bool enableClick;
  final bool fillBlank; //是否填充填空
  final List<GlobalKey> keys = [];

  void test(String text) {
    if (text == ' ') {
      _log.info('遍历=空格');
    } else if (text == '\n') {
      _log.info('遍历=换行');
    } else {
      _log.info('遍历=$text');
    }
  }

  Color _getTextColor(BuildContext context, QuestionItem item) {
    Color color = Colors.black;

    return color;
  }

  List<QuestionItem> getQuestionItems() {
    List<QuestionItem> _questions = [];
    int startIndex = 0;
    int _blankNum = 0; //填空的个数
    String testStr = dataItem.text.name;
    List<String> strList = testStr.split('___');
    for (int i = 0; i < strList.length; i++) {
      String ss = strList[i];
      if (i > 0) {
        _questions.add(QuestionItem()
          ..text = '(${startIndex + 1})'
          ..isBlank = false
          ..exerciseId = 'exerciseId');

        String standard = '';
        _questions.add(QuestionItem()
          ..text = '          '
          ..isBlank = true
          ..pageIndexStrForLarge = '第 ${startIndex + 1} 题'
          ..isRight = true
          ..explanation = 'sdfsdfdsf'
          ..standard = standard
          ..exerciseId = 'exerciseId');
        startIndex++;
        _blankNum++;
      }
      RegExp expNewLine = RegExp(r'([\n])');
      List<String> newLineList = ss.split(expNewLine);
      // _log.info('newLineList:${newLineList.length}');
      for (int w = 0; w < newLineList.length; w++) {
        String newLineItem = newLineList[w];
        if (w > 0 && newLineItem.trim().isNotEmpty) {
          _questions.add(QuestionItem()
            ..text = '\n'
            ..isBlank = false);
          // _log.info('换行后面内容:$newLineItem');
        }
        // 根据分隔符拆分会导致text渲染的时候排版不紧凑，每个text被换行显示了，因此拆分力度细化到单词
        RegExp exp = RegExp(r'(\s)');
        List<String> words = newLineItem.split(exp);
        for (int k = 0; k < words.length; k++) {
          String word = words[k];
          if (k > 0) {
            _questions.add(QuestionItem()
              ..text = ' '
              ..isBlank = false);
          }
          if (word.isNotEmpty) {
            _questions.add(QuestionItem()
              ..text = word
              ..isBlank = false);
          }
        }
      }
      // _log.info('拆分:$ss');
    }
    return _questions;
  }

  List<TextSpan> _buildText(BuildContext context, List<GlobalKey> keys) {
    List<TextSpan> result = [];
    GlobalKey _getKey(int index) {
      GlobalKey key;
      try {
        key = keys[index];
      } catch (e) {}
      return key;
    }

    List<QuestionItem> questions = getQuestionItems(); //TODO
    // _log.info('**********');
    for (int index = 0; index < questions.length; index++) {
      // test(questions[index].text);
      TextDecoration textDecoration;
      if (questions[index].isBlank) {
        textDecoration = TextDecoration.underline;
      }
      GestureRecognizer recognizer = TapGestureRecognizer()..onTap = () {};
      result.add(TextSpan(
        children: <InlineSpan>[
          if (maxLines == null)
            WidgetSpan(
              child: SizedBox(
                width: 1.0,
                height: 1.0,
                key: _getKey(index),
              ),
            ),
          TextSpan(
              text: '${questions[index].text}!',
              recognizer: enableClick ? recognizer : null,
              style: TextStyle(
                  decoration: textDecoration,
                  decorationColor: Colors.black,
                  fontSize: flexible(context, 12.0),
                  color: _getTextColor(context, questions[index]))),
          // WidgetSpan(
          //     child: Container(
          //       color: Colors.yellowAccent,
          //       margin: EdgeInsets.all(2.0),
          //       child: RichText(
          //           text: TextSpan(
          //               text: '${questions[index].text}',
          //               recognizer: enableClick ? recognizer : null,
          //               style: TextStyle(
          //                   decoration: textDecoration,
          //                   decorationColor: Colors.black,
          //                   fontSize: flexible(context, 8.0),
          //                   color: _getTextColor(context, questions[index])))),
          //     )),
        ],
      ));
    }
    return result;
  }

  @override
  Widget build(BuildContext context) {
    return RichText(
      maxLines: maxLines,
      overflow: maxLines != null ? TextOverflow.ellipsis : TextOverflow.clip,
      text: TextSpan(children: _buildText(context, keys), style: TextStyle(height: flexible(context, defaultTextHeight))),
    );
  }
}

class QuestionItem {
  String text;
  bool isBlank; //是否是横线
  String exerciseId;
  bool isRight; //用户是否做对
  String pageIndexStrForLarge; //第 xx 题
  String standard; //标准答案
  String explanation; //答案解析
}
